﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using UnityEngine;

namespace YeqianFramework.common
{
	public static class XmlHelper
	{
		/// <summary>
		/// 对象转XML
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="path">xml路径</param>
		/// <returns></returns>
		public static T Xml2Object<T>(string path)
		{
			T ret = default;
			using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
			{
				XmlSerializer xs = new XmlSerializer(typeof(T));
				ret = (T)xs.Deserialize(fs);
			}

			return ret;
		}
		public static object Xml2Object(string path, Type type)
		{
			object ret = null;
			using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
			{
				XmlSerializer xs = new XmlSerializer(type);
				ret = xs.Deserialize(fs);
			}

			return ret;
		}

		/// <summary>
		/// 对象转XML
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="path">xml路径</param>
		/// <param name="obj"></param>
		public static void Object2Xml<T>(string path, T obj)
		{
			using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
			{
				XmlSerializer xs = new XmlSerializer(obj.GetType());
				xs.Serialize(fs, obj);
			}
		}

		public static int String2Int(string val)
		{
			int resultVal = 0;
			if(!int.TryParse(val,out resultVal))
			{
				YQLogCenter.Current.LogError(string.Format("参数值 {0} 无法转换为整数", val));
				return 0;
			}
			return resultVal;
		}
	}
}
